package com.sam.im.heiqun.callmain;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.app.App;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.fragments.PlayFragment;
import com.sam.im.heiqun.uis.fragments.PushFragment;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.skyfishjy.library.RippleBackground;
import com.yuyh.library.view.image.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.webrtc.MediaConstraints;
import org.webrtc.MediaStream;
import org.webrtc.PeerConnection;
import org.webrtc.PeerConnectionFactory;
import org.webrtc.RendererCommon;
import org.webrtc.VideoRenderer;
import org.webrtc.VideoRendererGui;
import org.webrtc.VideoSource;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.socket.client.Ack;
import io.socket.client.Socket;

public class Maincallactivity extends AppCompatActivity implements RtcListener {
    @BindView(R.id.bt_cancle)
    ImageView btCancle;
    @BindView(R.id.tv_cancle)
    TextView tvCancle;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.tv_witing)
    TextView tvWiting;
    @BindView(R.id.content)
    RippleBackground background;
    @BindView(R.id.tb_switch)
    ImageView tbSwitch;
    private VideoRenderer.Callbacks localRender;
    private VideoSource videoSource;
    private GLSurfaceView myVideoView;
    public PeerConnectionParameters pcParams;
    private int vWidth = 100;
    private int vHeight = 300;
    private MediaConstraints pcConstraints;
    private PopupWindow smallpup;
    private RelativeLayout parentview;
    private PlayFragment playFragment;
    private PushFragment pushFragment ;
    private static int START_LOCATION = 999;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            // 需要做的事:发送消息
            Message message = new Message();
            message.what = START_LOCATION;
            myhandler.sendMessage(message);
        }
    };
    Timer timer = new Timer();
    private int firsttag = -1;
    private boolean iscalling;//视屏中。。。。
    private MediaPlayer media;
    public static int CALL_VIDEO_CANCLE = 23311;
    public static int CALL_VIDEO_CANCLE_THE = 23310;
    private static Socket mSocket;
    private Camera camera;
    private Camera.Parameters parameters = null;
    private Handler myhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 999://对方长时间无响应
                    if (firsttag != -1) {
                        ToolsUtils.showToast(Maincallactivity.this, getResources().getString(R.string.call_other_no));
                        timer.cancel();
                        background.stopRippleAnimation();
                        if (media != null && media.isPlaying()) {
                            media.stop();
                        }
                        setResult(CALL_VIDEO_CANCLE);
                        finish();
                    }
                    firsttag++;
                    break;
            }
        }
    };
    private String type;
    private String headurl;
    private String name;
    private LinkedList<PeerConnection.IceServer> iceServers =  new LinkedList<>();


    public void initWebrtc() throws Exception {
        if (PeerConnectionFactory.initializeAndroidGlobals(
                this,
                true,
                true,
                true)) {
            Log.i("info","webrtc初始化成功");
        } else {
            Log.i("info","webrtc初始化失败");
        }
        //获取配置
        iceServers = RtcUtil.getIceServers();
        pcConstraints = RtcUtil.getPcConstraints();
        pcParams = RtcUtil.getConnParameter(this.getWindow());
        //初始化pc factory
        App.pcFactory = new PeerConnectionFactory();
        //创建一个pc连接
        App.pc = App.pcFactory.createPeerConnection(iceServers, pcConstraints, new RtcConnObserver(this));
        myVideoView = (GLSurfaceView) findViewById(R.id.myVideo);
        myVideoView.setPreserveEGLContextOnPause(true);
        myVideoView.setKeepScreenOn(true);
        VideoRendererGui.setView(myVideoView, new Runnable() {
            @Override
            public void run() {
            }
        });
        localRender = VideoRendererGui.createGuiRenderer(0, 0,
                vWidth, vWidth, RendererCommon.ScalingType.SCALE_ASPECT_FILL, false);
        // switchcamera();
        setframent();
        //启动摄像头
        RtcUtil.startCamera(this, pcParams, videoSource,RtcUtil.FONT_FACTING);
    }
    private void setframent() {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        playFragment = new PlayFragment();
        fragmentTransaction.add(R.id.framelayout_small, playFragment);
        fragmentTransaction.commit();
        /*FragmentTransaction fragmentTransaction1 = supportFragmentManager.beginTransaction();
        pushFragment = new PushFragment();
        fragmentTransaction1.add(R.id.framelayout_big,pushFragment);
        fragmentTransaction1.commit();*/
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        setContentView(R.layout.callmain_layout);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        App.iscallvideoing = false;
        headurl = getIntent().getStringExtra("headurl");
        type = getIntent().getStringExtra("type");
        if (type != null && type.equals("21")) {
            iscalling = true;
            btCancle.setVisibility(View.GONE);
            tvCancle.setVisibility(View.GONE);
        } else if (type.equals("0")) {
            media = MediaPlayer.create(this, R.raw.phonering);
            media.setLooping(true);
            media.start();
            background.setVisibility(View.VISIBLE);
            background.startRippleAnimation();
            Glide.with(this).load(headurl).centerCrop().into(imgIcon);
        }
        try {
            initWebrtc();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*if (!PermissionUtils.checkPermission(this, Manifest.permission.RECORD_AUDIO, 100)) {
            return;
        }
        if (PermissionUtils.checkPermission(this, Manifest.permission.CAMERA, 100)) {
            return;
        }*/
        if (type != null && type.equals("21")) {
            getmessage("1", Constant.MESSAGE_TYPR_CALL_VIDEO_AS, ChatRecyclerAdapter.TO_USER_CALLVIDEO_AS);
        }
    }

    @Override
    public void onCallReady(String callId) {

    }

    @Override
    public void onStatusChanged(String newStatus) {

    }

    @Override
    public void onLocalStream(MediaStream localStream) {
        //Log.i("info", "onLocalStream: ==="+pushFragment+"==="+localRender);
        localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
        VideoRendererGui.update(localRender,
                0, 0,
                vWidth, vWidth,
                RendererCommon.ScalingType.SCALE_ASPECT_FILL, false);
    }

    @Override
    public void onAddRemoteStream(MediaStream remoteStream) {
        remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(playFragment.remoteRender));
        VideoRendererGui.update(playFragment.remoteRender,
                0, 0,
                vWidth, vWidth, RendererCommon.ScalingType.SCALE_ASPECT_FILL, true);
        VideoRendererGui.update(localRender,
                0, 0,
                vWidth, vWidth,
                RendererCommon.ScalingType.SCALE_ASPECT_FILL, true);
    }
    @Override
    public void onRemoveRemoteStream() {
        //Log.i("info", "onRemoveRemoteStream: ===");
        //App.pc.removeStream(mediaStream);
        VideoRendererGui.update(localRender,
                0, 0,
                vWidth, vWidth,
                RendererCommon.ScalingType.SCALE_ASPECT_FILL, true);
    }
    private boolean isResume = false;

    @Override
    public void onPause() {
        super.onPause();
        myVideoView.onPause();
        App.pc.dispose();
        RtcUtil.disposd();
        if (App.pc != null) {
            App.pc = null ;
        }
        if (videoSource != null) {
            videoSource.dispose();
            videoSource.stop();
            isResume = true;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        myVideoView.onResume();
        if (videoSource != null && isResume) {
            videoSource.restart();
            isResume = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        App.iscallvideoing = false;
        if (media != null) {
            media.stop();
        }
        try {
            if (pcConstraints != null) {
                pcConstraints = null ;
            }
            if (iceServers != null) {
                iceServers.remove();
            }


            VideoRendererGui.remove(localRender);
            VideoRendererGui.remove(playFragment.remoteRender);
            VideoRendererGui.dispose();

            //App.pc.removeStream();
            //App.pc.dispose(); // 释放导致底层crash 暂时不进行资源释放

            App.pcFactory.dispose();
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {

        }
    }

    @Override
    public void onStop() {
        finish();
        super.onStop();
        //System.exit(0);
    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void getCallMessage(ImMessage imMessage) {
        if (imMessage != null && imMessage.getMessageType() == Constant.MESSAGE_TYPR_CALL_VIDEO_AS) {
            Log.i("info", "imessage==" + imMessage.toString());
            switch (imMessage.getContent()) {
                case "0":
                    timer.cancel();
                    ToolsUtils.showToast(Maincallactivity.this, getString(R.string.refouseyourvideorequst));
                    finish();
                    break;
                case "1":
                    timer.cancel();
                    iscalling = true;
                    ToolsUtils.showToast(Maincallactivity.this, getString(R.string.acceptyourvideorequst));
                    RtcUtil.createOffer(App.observer, pcConstraints);
                    if (media != null && media.isPlaying()) {
                        media.stop();
                    }
                    btCancle.setVisibility(View.GONE);
                    tvCancle.setVisibility(View.GONE);
                    background.stopRippleAnimation();
                    background.setVisibility(View.GONE);
                    break;
                case "2"://对方中断了当前视屏通话
                    ToolsUtils.showToast(Maincallactivity.this, getString(R.string.cutyourvideochat));
                    if (media != null && media.isPlaying()) {
                        media.stop();
                    }
                    finish();
                    break;
                case "3"://对方正在进行视屏通话
                    ToolsUtils.showToast(Maincallactivity.this, getString(R.string.yourfriendisbusy));
                    if (media != null && media.isPlaying()) {
                        media.stop();
                    }
                    break;
            }
            background.stopRippleAnimation();
        } else if (imMessage != null && imMessage.getMessageType() == Constant.MESSAGE_TYPR_CALL_VIDEO_AS) {
            if (imMessage.getContent().equals("0")) {
                getmessage("3", Constant.MESSAGE_TYPR_CALL_ANSWER, ChatRecyclerAdapter.TO_USER_CALLVIDEO_AS);//正在视屏 不能接受新的视屏
            }
        }
    }

    private void getmessage(String content, int type, int msgtype) {
        setSocket();
        long currentTime = System.currentTimeMillis();
        String fromid = ToolsUtils.getMyUserId();
        ImMessage imMessage = ToolsUtils.getTbub(Constant.VERSION_MESSAGE_CHART, Constant.DEV_TYPE, 0, msgtype, "1-" + App.rtcdestid + "-" + fromid + "-" + System.currentTimeMillis(),
                Long.parseLong(fromid), Constant.FROM_TYPE_MAM, Long.parseLong(App.rtcdestid), content, type,
                currentTime, System.currentTimeMillis(), 0, "", fromid + "_" + App.rtcdestid, 0, ToolsUtils.getUser().getHeadUrl());
        if (content.equals("3")) {
            imMessage.save();
        }
        Log.i("info", "===" + imMessage);
        //EventBus.getDefault().post(imMessage);
        socketSend(imMessage);
    }
    private void setSocket() {
        mSocket = App.socket;
        if (mSocket == null || !mSocket.connected()) {//mSocket 为空  这个基本不会出现 、或者链接断开了
            EventBus.getDefault().post(Constant.NOT_NET_SERVICE);
            String savesocketstr = ToolsUtils.savesocketstr(this, "", "", 2);
            String[] split = savesocketstr.split("___");
            App.initSocket(split[0], split[1]);
        }
    }

    /**
     * socket发送消息
     *
     * @param tbub
     */
    public void socketSend(final ImMessage tbub) {
        new Thread(new Runnable() {
            boolean sendState = false;
            int retryCount = 0;
            @Override
            public void run() {
                tbub.save();
                ImMessage imMessage = ImMessage.findById(ImMessage.class, tbub.getId());
                socketSend(imMessage);
            }

            @TargetApi(Build.VERSION_CODES.KITKAT)
            private void socketSend(final ImMessage imMessage) {
                while (!sendState && retryCount < 10) {
                    mSocket = App.socket;
                    retryCount++;
                    if (mSocket != null) {
                        mSocket.emit(Constant.EVENT, IMMessageToJson.changeJSONObject(imMessage), new Ack() {
                            @Override
                            public void call(Object... args) {
                                imMessage.setSendState(Constant.COMPLETED);
                                tbub.setSendState(Constant.COMPLETED);
                                if (imMessage.getMessageType() != Constant.MESSAGE_TYPR_READ) {
                                    imMessage.delete();
                                }
                                //sendMessageHandler.sendEmptyMessage(SEND_OK);
                                sendState = true;
                            }
                        });
                    }
                    try {
                        Thread.sleep(Constant.SOCKET_SEND_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void showdialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.tip_exit));
        builder.setMessage(getResources().getString(R.string.you_exit_spcall));
        builder.setNegativeButton(getResources().getString(R.string.clean), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getmessage("2", Constant.MESSAGE_TYPR_CALL_VIDEO_AS, ChatRecyclerAdapter.TO_USER_CALLVIDEO_AS);
                ToolsUtils.showToast(Maincallactivity.this, getResources().getString(R.string.spcall_dk));
                finish();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();//这里要在初始完之后进行设置
        alertDialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.blue));
        alertDialog.getButton(android.app.AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (iscalling) {
                showdialog();
            } else {
                setResult(CALL_VIDEO_CANCLE);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @OnClick({R.id.bt_cancle, R.id.tb_switch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_cancle:
                if (media != null && media.isPlaying()) {
                    media.stop();
                }
                background.stopRippleAnimation();
                setResult(CALL_VIDEO_CANCLE);
                finish();
                break;
            case R.id.tb_switch:
                RtcUtil.switchCamera();
               // switchcamera();
                break;
        }
    }
}
